<template >
  <div class="common-layout">
    <el-container>
      <el-header style="font-size: 30px">个人信息</el-header>
     <el-container>
      <el-aside width="400px"  style="background-color: white;">
         <div>
           <el-avatar :size="150" style="margin-top: 20px;margin-left: 125px"
              :src="infoForm.photoUrl"
           />
           <div>
               <el-upload
                   class="avatar-uploader"
                   action="http://localhost:8080/file/upload"
                   method="POST"
                   :show-file-list="false"
                   :on-progress="handlePreview"
                   :on-success="handleAvatarSuccess"
                   :auto-upload="true"
                   v-loading="loading"
               >
              <el-button class="button" :icon="UploadFilled"><span class="text">修改头像</span></el-button>
               </el-upload>
           </div>
         </div>
        <div style="width: 100%;height: 244px;border-top:10px rgb(248, 248, 248) solid">
          <el-button class="button" style="margin-top: 102px;" @click="centerDialogPassword = true" :icon="Edit"><span class="text">修改密码</span></el-button>
          <el-dialog
              v-model="centerDialogPassword"
              title="密码修改"
              width="500"
              align-center
          >
            <el-form
                ref="updateFormRef"
                id="form"
                :model="updateForm"
                :rules="passwordRules"
                label-width="auto"
                class="demo-infoForm"
            >
            <el-form-item label="旧密码&nbsp;&nbsp;&nbsp;&nbsp;" prop="oldPassword">
              <el-input v-model="updateForm.oldPassword"/>
            </el-form-item>
            <el-form-item label="新密码&nbsp;&nbsp;&nbsp;&nbsp;"  prop="password">
              <el-input v-model="updateForm.password"/>
            </el-form-item>
            <el-form-item label="确认密码"  prop="confirmPassword">
              <el-input v-model="updateForm.confirmPassword" />
            </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="centerDialogPassword = false">取消</el-button>
                <el-button type="primary" @click="updatePassword(updateFormRef)">
                  确认修改
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
       </el-aside>
       <el-main >
         <el-form
             ref="infoFormRef"
             style="max-width: 600px"
             :model="infoForm"
             :rules="rules"
             label-width="auto"
             class="demo-infoForm"
             :size="formSize"
             status-icon
         >
           <el-form-item label="姓名" prop="realName">
             <el-input v-model="infoForm.realName" />
           </el-form-item>
           <el-form-item label="性别" prop="sex">
             <el-radio-group v-model="infoForm.sex">
               <el-radio label="男"   value="1"/>
               <el-radio label="女"   value="0"/>
             </el-radio-group>
           </el-form-item>
           <el-form-item label="手机号" prop="phone">
             <el-input v-model="infoForm.phone" />
           </el-form-item>
           <el-form-item label="组织" prop="organizationName">
             <el-input v-model="infoForm.organizationName" readonly />
           </el-form-item>
           <el-form-item label="岗位名称" prop="jobName">
             <el-input v-model="infoForm.jobName" readonly />
           </el-form-item>
           <el-form-item label="薪资(RMB)" prop="salary">
             <el-input v-model="infoForm.salary" readonly />
           </el-form-item>
           <el-form-item label="入职日期" prop="joinDate">
             <el-input v-model="infoForm.joinDate" readonly />
           </el-form-item>
           <el-form-item label="离职日期" prop="leaveDate">
             <el-input v-model="infoForm.leaveDate" readonly />
           </el-form-item>
             <el-button class="phone" @click="centerDialogPhone=true" :icon="PhoneFilled"><span class="text">修改个人信息</span></el-button>
            <el-dialog v-model="centerDialogPhone" title="警告" width="500" center>
        <span style="padding-left: 160px">
            确认修改个人信息嘛？
        </span>
             <template #footer>
               <div class="dialog-footer">
                 <el-button @click="centerDialogPhone = false">取消</el-button>
                 <el-button type="primary" @click="submitForm(infoFormRef)">
                   确认修改
                 </el-button>
               </div>
             </template>
           </el-dialog>
         </el-form>
       </el-main>
     </el-container>
    </el-container>
  </div>
</template>
<script setup>
import { reactive, ref,onMounted } from 'vue'
import {useStaffStaffStore} from "@/stores/staff.js";
import {UploadFilled,Edit,PhoneFilled}  from '@element-plus/icons-vue'
import axiosInstance from "@/axios/index.js";
import {ElMessage,ElNotification} from "element-plus";
import router from "@/router/index.js";
const formSize = ref('default')
const updateFormRef= ref()
const infoFormRef = ref()
const staff= useStaffStaffStore().staffInfo.staff


const infoForm = reactive({
  realName:staff.realName,
  sex:staff.gender.toString(),
  phone:staff.phone,
  organizationName:useStaffStaffStore().staffInfo.organizationName,
  jobName:staff.jobName,
  salary:staff.salary,
  joinDate:staff.joinDate,
  leaveDate:staff.leaveDate,
  photoUrl:staff.photoUrl,
  staffNo:staff.staffNo
})

//表单填写规则
const rules = reactive({
  phone: [
    { required: true, message: '请输入手机号' ,trigger: 'blur'},
    {min: 11, max: 11, message: '长度必须为11个字符'}
  ],
  realName: [
    { required: true, message: '请输入姓名' ,trigger: 'blur'},
  ],
  sex: [
    { required: true, message: '请输入性别' ,trigger: 'blur'},
  ]
})

//密码表单
const updateForm = reactive({
  oldPassword: '',
  password: '',
  confirmPassword:'',
  photoUrl:''
})

onMounted(() => {
  if(useStaffStaffStore().staffInfo.staff.isFirstLogin===1){
    open()
  }
});
const open = () => {
  ElNotification({
    title: '提示',
    message: '首次登陆，请修改密码',
    type: 'warning',
  })
}
//确认输入旧密码密码是否正确
const validatePassword = (rule, value, callback) => {
    if (value !== staff.password) {
      callback(new Error('旧密码输入错误'))
    } else {
      callback()
    }
}

//确认输入旧密码密码是否正确
const validateConfirm = (rule, value, callback) => {
    if (value !== updateForm.password) {
      callback(new Error('两次输入密码不一致'))
    } else {
      callback()
    }
}

//密码表单校验规则
const passwordRules = reactive({
  oldPassword:[
      { required: true, message: '请输入新密码', trigger: 'blur'},
      { min: 6, max: 20, message: '长度在 6 到 20 个字符'},
      { validator:validatePassword,  trigger: 'blur'}
  ],
  confirmPassword:[
    { required: true, message: '请输入新密码', trigger: 'blur'},
    { min: 6, max: 20, message: '长度在 6 到 20 个字符'},
    { validator:validateConfirm, trigger: 'blur'}
  ],
  password:[
      { required: true, message: '请输入新密码', trigger: 'blur'},
      { min: 6, max: 20, message: '长度在 6 到 20 个字符'},
  ]
})

const loading=ref(false)

//点击文件列表中已上传的文件时的钩子
const handlePreview = () => {
    loading.value=true
}

//修改密码弹窗提示
const centerDialogPassword = ref(false)

//修改手机弹窗提示
const centerDialogPhone =ref(false)

//修改密码
const updatePassword = (formEl) => {
  if (!formEl) return
   formEl.validate((valid) => {
     if (valid) {
       centerDialogPassword.value = false
       if (updateForm.oldPassword !== updateForm.confirmPassword) {
         axiosInstance.post('/staff/updateInfo', {
           staffNo: staff.staffNo,
           password: updateForm.password,
         }).then(
             (res) => {
               if (res.data.code === 200) {
                 router.push('/login')
                 ElMessage({
                   message: '修改成功',
                   type: 'success',
                   duration: 500,
                 })
               } else {
                 ElMessage({
                       message: "修改失败",
                       type: 'error',
                       duration: 500,
                     }
                 )
               }
             })
       } else {
         ElMessage({
           message: ' 不能修改相同的密码',
           type: 'error',
           duration: 500,
         })
       }
     }
   })
}
//头像上传成功
function handleAvatarSuccess( response, uploadFile){
  if(response.code===500){
    ElMessage({
      message: response.message,
      type: 'error',
      duration: 500,
    })
  }else{
    updateForm.photoUrl=response.data
    ElMessage({
      message: response.message,
      type: 'success',
      duration: 500,
    })
  }
  loading.value=false
}


//修改手机号
const submitForm =(formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      centerDialogPhone.value = false
      if (infoForm.phone !== staff.phone) {
        axiosInstance.post('/staff/updateInfo', {
          staffNo: staff.staffNo,
          phone: infoForm.phone,
          realName:infoForm.realName,
          gender:infoForm.sex,
          photoUrl:updateForm.photoUrl
        }).then(
            (res) => {
              if (res.data.code === 200) {
                staff.phone=infoForm.phone
                ElMessage({
                  message: '修改成功',
                  type: 'success',
                  duration: 500,
                })
              } else {
                ElMessage({
                      message: '修改失败',
                      type: 'error',
                      duration: 500,
                    }
                )
              }
            })
      } else {
        ElMessage({
          message: ' 修改成功',
          type: 'success',
          duration: 500,
        })
      }
    }
  })
}


</script>

<style scoped>
.button{
  margin-left: 120px;
  margin-top: 30px;
  margin-bottom: 30px;
  width: 150px;
  height: 40px;
  background-color: rgb(114, 114, 114);
  border-radius: 5px;
  border: 1px;
  color: white;
}
.phone {
  width: 519px;
  height: 40px;
  border-radius:5px;
  border: 1px;
  margin-top: 20px;
  margin-left: 80px;
  background-color:rgb(64, 158, 255);
  color: white;
}
.text{
  padding-top: 1px;
}
</style>
